const util = require('./utils');
const logger = util.getLogger(__filename);
const Mix = require('./controller/Mix');
const Individual = require('./controller/Individual');
const EndWithMeetingId = require('./controller/EndWithMeetingId');
const m = require('./controller/monitor');
const lock = new Map();

function MessageRouter(msg) {
	return new Promise((resolve, reject) => {
		let { envelope, core } = msg;
		let { routing, timestamp, name } = envelope
		let { header, body } = core;
		let { operation, name: headerName } = header;
		let { events, args } = body;
		logger.info(`【MessageRouter】[${new Date(timestamp).toISOString()}] get Message:${JSON.stringify(msg)}`)
		const { meetingId, uid, channelName } = args
		const key = `${headerName}:${operation}:${meetingId}:${channelName}:${uid}`
		if (lock.has(key)) {
			return resolve('执行中')
		}
		lock.set(key, msg)
		let controller = undefined;
		switch (name) {
			case 'ScreenShare':
				controller = new Individual(args, events)
				break;
			case 'VideoMix':
				controller = new Mix(args, events)
				break;
			case 'EndWithMeetingId':
				controller = new EndWithMeetingId(args.meetingId)
		}
		if (!controller && !controller[operation]) {
			logger.error(`未知消息结构:${JSON.stringify(msg)}`)
			return reject({ msg: '未知消息' })
		}
		controller[operation]().then(resolve).catch(err => {
			logger.error('最后的处理')
			logger.error(err)
			reject({ msg: '操作错误' })
		}).finally(() => {
			lock.delete(key)
			logger.info('delete lock.' + key)
		})
	})
}

module.exports = { MessageRouter, lock }
